import React, { useState, useEffect, useCallback } from 'react';
import { Button, Form, Input, DatePicker, Table, Select, TreeSelect } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import moment from 'moment';
import { flatTryCatch } from '../../../../servers/http';
import { getBatchList, getOrganTree } from 'admin/servers/servers';
import { debounce } from 'lodash';
import { invariableCol } from './constant';

const { RangePicker } = DatePicker;
const timeFormat = 'YYYY-MM-DD';
const { Option } = Select;

const BatchRecord: React.FC = () => {
  const [form] = Form.useForm();
  const [tableDataList, setTableDataList] = useState([]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => `共${total}条`,
  });

  /** organ */
  const [organTree, setOrganTree] = useState([]);
  const fetchOrganTree = useCallback(async () => {
    const { response, error } = await flatTryCatch(getOrganTree({ orgPid: 0 }));
    if (error) return;
    setOrganTree(response.data);
  }, []);

  useEffect(() => {
    fetchOrganTree();
  }, [fetchOrganTree]);

  /** table */
  const columns: ColumnsType = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pagination.pageSize * (pagination.current - 1),
      width: 80,
      fixed: 'left',
    },
    ...invariableCol,
  ];

  /** 获取数据 */
  const fetchDataList = useCallback(async (values: any, page: number, limit: number) => {
    setTableLoading(true);
    const params = { page, limit, ...values };
    if (params.timeRange) {
      const [start, end] = params.timeRange;
      params.startTime = moment(start).format(timeFormat);
      params.endTime = moment(end).format(timeFormat);
    }
    delete params.timeRange;

    const { response, error } = await flatTryCatch(getBatchList(params));
    setTableLoading(false);
    if (error) return;

    const { totalCount = 0, list = [], currPage = 1, pageSize = 10 } = response.page ?? {};
    setTableDataList(list);
    setPagination({
      current: currPage,
      pageSize,
      total: totalCount,
      showTotal: (total: number) => `共${total}条`,
    });
  }, []);

  /**操作: 搜索 */
  const handleFinish = debounce((values: any) => {
    fetchDataList(values, 1, pagination.pageSize);
  }, 500);

  /**操作: 重置 */
  const handleReset = debounce(() => {
    form.resetFields();
    fetchDataList({}, 1, 10);
  }, 500);

  /**操作: 页码改变 */
  const handleTableChange = newPagination => {
    setPagination(newPagination);
    fetchDataList(form.getFieldsValue(), newPagination.current, newPagination.pageSize);
  };

  useEffect(() => {
    fetchDataList({}, 1, 10);
  }, [fetchDataList]);

  return (
    <div className="page-main-container">
      <Form layout="inline" form={form} onFinish={handleFinish} style={{ marginBottom: '20px' }}>
        <Form.Item label="机构名称" name="orgId">
          <TreeSelect
            showSearch
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择机构名称"
            allowClear
            treeData={organTree}
            fieldNames={{ label: 'name', value: 'id' }}
            style={{ width: 140 }}
          />
        </Form.Item>
        <Form.Item label="批次时间" name="timeRange">
          <RangePicker format={timeFormat} style={{ width: 220 }} />
        </Form.Item>
        <Form.Item label="任务名称" name="name">
          <Input placeholder="请输入任务名称" style={{ width: 140 }} />
        </Form.Item>
        <Form.Item label="发送方式" name="timeType">
          <Select placeholder="请选择发送方式" allowClear style={{ width: 140 }}>
            <Option value={1}>立即发送</Option>
            <Option value={2}>定时发送</Option>
          </Select>
        </Form.Item>
        <Form.Item label="批次内容" name="msg">
          <Input placeholder="请输入批次内容" style={{ width: 140 }} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <Table
        loading={tableLoading}
        dataSource={tableDataList}
        columns={columns}
        rowKey="id"
        pagination={pagination}
        scroll={{ x: 'max-content', y: window.innerHeight - 340 }}
        onChange={handleTableChange}
      />
    </div>
  );
};

export default BatchRecord;
